package com.sservice.web.wechat.controller;

import com.github.binarywang.wxpay.util.SignUtils;
import com.sservice.base.Utils;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.web.wechat.service.WxMpService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 微信公众号开发接口
 */
@Controller
@RequestMapping("/wx/mp")
public class WxMpController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass()); //
    @Autowired
    private WxMpService wxMpService;

    /**
     * jssdk 配置
     *
     * @param url
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/jssdk-config", method = {RequestMethod.GET})
    public BaseResult wxJsSdk(String url) throws WxErrorException {
        Map map = new TreeMap();
        logger.debug("[wxMpService.getJsapiTicket()]=" + wxMpService.getJsapiTicket());
        map.put("jsapi_ticket", wxMpService.getJsapiTicket());
        map.put("noncestr", Utils.getNonceStr());
        map.put("timestamp", Utils.getSec());
        map.put("url", url);
        Map map1 = new HashMap();
        map1.put("signature", SignUtils.createSign(map, null, wxMpService.getWxMpConfigStorage().getAesKey(), true));
        map1.put("appId", wxMpService.getWxMpConfigStorage().getAppId());
        map1.put("nonceStr", map.get("noncestr"));

        return new BaseResult(true, map1);
    }

    /**
     * 静默授权获取用户信息
     *
     * @param url
     * @return
     * @throws WxErrorException
     */
    @RequestMapping(value = "/auth", method = {RequestMethod.GET})
    public String auth(String url) throws WxErrorException {
        url = "http://www.hpchem.cn/api/wx/mp/getinfo";
        return "redirect:" + wxMpService.oauth2buildAuthorizationUrl(url, "snsapi_base", "hp");
    }

    /**
     * 静默授权获取用户openid
     *
     * @param code
     * @return
     * @throws WxErrorException
     */
    @RequestMapping(value = "/getinfo", method = {RequestMethod.GET})
    public String auth1(String code) throws WxErrorException {
        WxMpOAuth2AccessToken token = wxMpService.oauth2getAccessToken(code);
        return "redirect:http://www.hpchem.cn/wx/e-order/msds.html?openid=" + token.getOpenId();
    }


}